// Copyright 2018 github.com/andesli/gossh Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: andes
// Email: email.tata@qq.com

package output

import (
	//	"context"
	"fmt"
	"strings"

	"github.com/andesli/gossh/machine"

	//	"strings"
	"sync"
	"time"
)

const (
	TIMEOUT = 4500
)

//new print result
// func Print(res machine.Result) {
// 	fmt.Printf("ip=%s\n", res.Ip)
// 	//index := strings.Index(cmd, ";")
// 	//newcmd := cmd[index+1:]
// 	//fmt.Printf("ip=%s|command=%s\n", ip, cmd)
// 	fmt.Printf("command=%s\n", res.Cmd)
// 	if res.Err != nil {
// 		fmt.Printf("return=1\n")
// 		fmt.Printf("%s\n", res.Err)
// 	} else {
// 		fmt.Printf("return=0\n")
// 		fmt.Printf("%s\n", res.Result)
// 	}
// 	fmt.Println("----------------------------------------------------------")
// }

// 新逻辑,将comman,ip,result 打印到同一行
func Print(res machine.Result) {
	returnCode := 0
	if res.Err != nil {
		returnCode = 1
	}
	fmt.Printf("ip=%s|command=%s|return=%d\n", res.Ip, res.Cmd, returnCode)
	if res.Err != nil {
		fmt.Printf("%s\n", res.Err)
	} else {
		// fmt.Printf("%s\n", res.Result)
		for _, line := range strings.Split(res.Result, "\n") {
			fmt.Printf("%s\n", line)
		}

	}
	fmt.Println("----------------------------------------------------------")
}

// func PrintResults2(crs chan machine.Result, ls int, wt *sync.WaitGroup, ccons chan struct{}, timeout int) {
// 	if timeout == 0 {
// 		timeout = TIMEOUT
// 	}

// 	//增加调试
// 	fmt.Println(timeout)
// 	// 增加日志：观测超时参数和通道状态
// 	fmt.Printf("[DEBUG] 结果监听启动 | 超时=%ds | 通道容量=%d\n", timeout, cap(ccons)) // 🟢 新增

// 	for i := 0; i < ls; i++ {
// 		// select {
// 		// case rs := <-crs:
// 		// 	//PrintResult(rs.Ip, rs.Cmd, rs.Result)
// 		// 	Print(rs)
// 		// case <-time.After(time.Second * time.Duration(timeout)):
// 		// 	fmt.Printf("getSSHClient error,SSH-Read-TimeOut,Timeout=%ds", timeout)
// 		// }
// 		fmt.Printf("[RESULTS] 等待接收结果 | 剩余=%d | 时间=%s\n",
// 			ls-i, time.Now().Format("15:04:05.000")) // 🆕

// 		select {
// 		case rs := <-crs:
// 			// 增加日志：观测结果到达时间
// 			fmt.Printf("[DEBUG] 收到结果 | ip=%s | 时间=%s\n", rs.Ip, time.Now().Format("15:04:05.000")) // 🟢 新增
// 			// currentIP = rs.Ip
// 			Print(rs)
// 		case <-time.After(time.Second * time.Duration(timeout)):
// 			// 增加日志：明确超时事件
// 			fmt.Printf("[ERROR] 结果等待超时 | 时间=%s | 超时=%ds\n", time.Now().Format("15:04:05.000"), timeout) // 🟢 新增
// 			fmt.Printf("getSSHClient error, SSH-Read-TimeOut, Timeout=%d\n", timeout)
// 		}
// 		wt.Done()
// 		<-ccons
// 		// 增加日志：观测通道释放动作
// 		fmt.Printf("[DEBUG] 释放并发槽位 | 剩余任务=%d | 时间=%s\n", ls-i-1, time.Now().Format("15:04:05.000")) // 🟢 新增

// 	}

// }

func PrintResults2(crs chan machine.Result, ls int, wt *sync.WaitGroup, ccons chan struct{}, timeout int) {
	if timeout == 0 {
		timeout = TIMEOUT
	}

	fmt.Printf("[DEBUG] 结果监听启动 | 超时=%ds | 通道容量=%d\n", timeout, cap(ccons))

	for i := 0; i < ls; i++ {
		wt.Add(1)
		ccons <- struct{}{} // 占槽

		go func(i int) {
			defer wt.Done()
			defer func() { <-ccons }()

			select {
			case rs := <-crs:
				fmt.Printf("[DEBUG] 收到结果 | ip=%s | 时间=%s\n", rs.Ip, time.Now().Format("15:04:05.000"))
				Print(rs)
			case <-time.After(time.Second * time.Duration(timeout)):
				fmt.Printf("[ERROR] 结果等待超时 | 时间=%s | 超时=%ds\n", time.Now().Format("15:04:05.000"), timeout)
				fmt.Printf("getSSHClient error, SSH-Read-Time-Out, Timeout=%d\n", timeout)
			}
			fmt.Printf("[DEBUG] 释放并发槽位 | 剩余任务=%d | 时间=%s\n", ls-i-1, time.Now().Format("15:04:05.000"))
		}(i)
	}
}

// print push file result
func PrintPushResult(ip, src, dst string, err error) {
	fmt.Println("ip=", ip)
	fmt.Println("command=", "scp "+src+" root@"+ip+":"+dst)
	if err != nil {
		fmt.Printf("return=1\n")
		fmt.Println(err)
	} else {
		fmt.Printf("return=0\n")
		fmt.Printf("Push %s to %s ok.\n", src, dst)
	}
	fmt.Println("----------------------------------------------------------")
}

// print pull result
func PrintPullResult(ip, src, dst string, err error) {
	fmt.Println("ip=", ip)
	fmt.Println("command=", "scp "+" root@"+ip+":"+dst+" "+src)
	if err != nil {
		fmt.Printf("return=1\n")
		fmt.Println(err)
	} else {
		fmt.Printf("return=0\n")
		fmt.Printf("Pull from %s to %s ok.\n", dst, src)
	}
	fmt.Println("----------------------------------------------------------")
}
